package com.lzb.watermarkcamera.activity;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.watermarkcamera.BaseAc;
import com.lzb.watermarkcamera.R;
import com.lzb.watermarkcamera.adapter.AlbumChildAdapter;
import com.lzb.watermarkcamera.adapter.PhoneAlbumAdapter;
import com.lzb.watermarkcamera.basic.picselect.MediaLoadManager;
import com.lzb.watermarkcamera.basic.picselect.PhotoConfig;
import com.lzb.watermarkcamera.basic.picselect.SelectMediaEntity;
import com.lzb.watermarkcamera.basic.utils.RxUtil;
import com.lzb.watermarkcamera.bean.PhoneAlbumBean;
import com.lzb.watermarkcamera.databinding.ActivitySearchPictureBinding;
import com.lzb.watermarkcamera.dialog.PermissionExplainDialog;
import com.lzb.watermarkcamera.utils.MyMediaLoader;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

public class SearchPictureActivity extends BaseAc<ActivitySearchPictureBinding> implements OnItemClickListener {

    private PhoneAlbumAdapter mPhoneAlbumAdapter;
    private List<SelectMediaEntity> listAll = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_search_picture;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSearchPictureBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.rvPictureList.setLayoutManager(new LinearLayoutManager(mContext));
        mPhoneAlbumAdapter = new PhoneAlbumAdapter();
        mDataBinding.rvPictureList.setAdapter(mPhoneAlbumAdapter);
        mPhoneAlbumAdapter.setOnItemClickListener(this);

        // 监听软键盘搜索按钮
        mDataBinding.etName.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                String keyword = mDataBinding.etName.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    search(keyword);
                } else {
                    ToastUtils.showShort(R.string.please_input_picture_name);
                }
                return true;
            }
            return false;
        });
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        AlbumChildAdapter albumChildAdapter = (AlbumChildAdapter) adapter;
        PhoneAlbumBean.ClassBean item = albumChildAdapter.getItem(position);
        PicEditActivity.sImgPath = item.getPath();
        startActivity(PicEditActivity.class);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        getPermission();
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_picture_permission));
        List<String> permissionsInManifest = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissionsInManifest.add(Manifest.permission.READ_MEDIA_IMAGES);
            permissionsInManifest.add(Manifest.permission.READ_MEDIA_VIDEO);
        } else {
            permissionsInManifest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            permissionsInManifest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        PermissionUtils.permission(permissionsInManifest.toArray(new String[permissionsInManifest.size()])).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                getData();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    //获取视频和图片数据
    private void getData() {
        showDialog(getString(R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntity) {
                dismissDialog();
                listAll = selectMediaEntity;
                search(mDataBinding.etName.getText().toString());
            }
        });
    }

    private void search(String text) {
        List<SelectMediaEntity> listShow = new ArrayList<>();
        for (SelectMediaEntity selectMediaEntity : listAll) {
            if (selectMediaEntity.getMediaName().contains(text)) {
                listShow.add(selectMediaEntity);
            }
        }
        List<PhoneAlbumBean> phoneAlbumBeans = MyMediaLoader.getInstance().loadPicData(listShow, true);
        if (phoneAlbumBeans.size() > 0) {
            mPhoneAlbumAdapter.setList(phoneAlbumBeans);
            mDataBinding.rvPictureList.setVisibility(View.VISIBLE);
            mDataBinding.flPictureNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvPictureList.setVisibility(View.GONE);
            mDataBinding.flPictureNoData.setVisibility(View.VISIBLE);
        }
    }

}